package demo.account.controller;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import demo.MyConfiguration;
import demo.model.Account;
import demo.model.AccountResponseModel;

@RestController
@RequestMapping("/account")
public class AccountServiceController {
	
	Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private MyConfiguration configuration;

    @RequestMapping(value="/list/{name}")
    public ResponseEntity<AccountResponseModel> getAccountsByCustomerName(@PathVariable String name,@RequestParam String region) {
    	
    	List<Account> accounts = new ArrayList<Account>();
    	
    	accounts.add(new Account("1",10000D,name,region));
    	
    	return ResponseEntity.ok(new AccountResponseModel(configuration.getServiceId(),accounts));
    }
    
    @RequestMapping(value="/list")
    public ResponseEntity<AccountResponseModel>  getAccounts(@RequestParam String name,@RequestParam String region) throws Exception{
    	
    	logger.info("***{}:getAccountsByCustomerName({},{}) is called.",configuration.getServiceId(),name,region);
    	
    	//simulate hard exception
    	if("UK".equals(region)){    		
    		if(configuration.isAlwaysException()) {
    			throw new Exception("Unsupported region :" + region);
    		}
    	}
    	else if("US".equals(region)){
    		//simulate timeout exception
    		try{
    			Thread.sleep(configuration.getSleepInMilliseconds());
    		}catch(InterruptedException e){
    		}
    	}    	    	
    	return getAccountsByCustomerName(name,region);
    }
}
